package cn.edu.zafu.bigdata.x.Foo;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Scanner;

public class FileAppendOperations {

    // 追加内容到文件的方法
    public static void appendToFile(String fileName, String content) {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileName, true))) {
            writer.newLine(); // 添加一个新行
            writer.write(content);
        } catch (IOException e) {
            System.out.println("追加到文件时发生错误: " + e.getMessage());
        }
    }

    // 读取文件内容的方法
    public static void readFile(String fileName) {
        try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            System.out.println("读取文件时发生错误: " + e.getMessage());
        }
    }

    // 主方法，用于测试追加和读取文件的功能
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String rootDir = System.getProperty("user.dir");
        System.out.println("程序根目录" + rootDir);
        System.out.println("Please enter the text you want to append:");
        String text = scanner.nextLine();

        // 文件路径，假设files目录已经存在
        String fileName = rootDir + "/files/202211080117.txt";

        // 将用户输入的文本追加到文件
        appendToFile(fileName, text);

        // 读取并显示文件内容
        System.out.println("文本内容如下：");
        readFile(fileName);

        scanner.close();
    }
}
